package com.tongyi.modules.mld.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tongyi.common.exception.BusinessException;
import com.tongyi.common.utils.DateUtils;
import com.tongyi.common.utils.ShiroUtils;
import com.tongyi.common.utils.SmsUtil;
import com.tongyi.core.PageInfo;
import com.tongyi.modules.mld.controller.enums.StatusEnum;
import com.tongyi.modules.mld.controller.vo.MldCustomReservationVo;
import com.tongyi.modules.mld.entity.MldCustomReservationEntity;
import com.tongyi.modules.mld.service.IMldCustomReservationService;
import com.tongyi.modules.mld.service.MldCustomReservationService;
import com.tongyi.modules.mld.service.converter.MldCustomReservationVoConverter;
import com.tongyi.modules.sys.entity.SysDictEntity;
import com.tongyi.modules.sys.entity.SysUserEntity;
import com.tongyi.modules.sys.service.SysDictService;
import com.tongyi.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class IMldCustomReservationServiceImpl implements IMldCustomReservationService {

    @Autowired
    private MldCustomReservationService mldCustomReservationService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysDictService sysDictService;


    @Override
    public List<MldCustomReservationVo> listAll(Map<String, Object> params) {
        List<MldCustomReservationEntity> list = mldCustomReservationService.listAll(params);
        return MldCustomReservationVoConverter.convert2VoList(list);
    }

    @Override
    public PageInfo<MldCustomReservationVo> listPage(int current, int size, Map<String, Object> params) {
        PageInfo<MldCustomReservationEntity> pageInfo = mldCustomReservationService.listPage(current, size, params, ShiroUtils.getUserEntity());
        PageInfo<MldCustomReservationVo> pi = new PageInfo<>();
        pi.setList(MldCustomReservationVoConverter.convert2VoList(pageInfo.getList()));
        pi.setSize(pageInfo.getSize());
        pi.setCurrent(pageInfo.getCurrent());
        pi.setTotal(pageInfo.getTotal());
        return pi;
    }

    @Override
    public void update(MldCustomReservationEntity entity) {

        MldCustomReservationEntity dbEntity = mldCustomReservationService.getById(entity.getId());
        if (!StatusEnum.checkStatus(entity.getStatus(), dbEntity.getStatus())) {
            throw new BusinessException("不能修改此状态");
        }

        //如果是认领，则关联用户信息
        if (StatusEnum.claimed.name().equals(entity.getStatus())) {
            SysUserEntity sysUserEntity = ShiroUtils.getUserEntity();
            if (Objects.isNull(sysUserEntity)) {
                throw new BusinessException("用户登录过期或者未登录");
            }
            entity.setUserId(sysUserEntity.getUserId());
            entity.setUserName(sysUserEntity.getUserName());
            entity.setRealName(sysUserEntity.getRealName());
        }
        entity.setUpdateTime(new Date());
        List<SysDictEntity> sysDictEntities = sysDictService.queryByDistValues(Lists.newArrayList(entity.getDepartmentCode()));
        entity.setDepartment(Optional.ofNullable(sysDictEntities).map(list->list.get(0)).map(SysDictEntity::getName).orElse(null));
        mldCustomReservationService.updateEntity(entity);
    }

    @Override
    public void add(MldCustomReservationEntity entity) {
        if (StringUtils.isNotBlank(entity.getUserName())) {
            if (StatusEnum.init.name().equals(entity.getStatus())) {
                throw new BusinessException("状态非法");
            }
            SysUserEntity sysUserEntity = sysUserService.queryByUserName(entity.getUserName());
            if (Objects.nonNull(sysUserEntity)) {
                entity.setUserId(sysUserEntity.getUserId());
                entity.setRealName(sysUserEntity.getRealName());
            }
        }
        Date createTime = new Date();
        entity.setUpdateTime(new Date());
        entity.setCreateTime(createTime);
        List<SysDictEntity> sysDictEntities = sysDictService.queryByDistValues(Lists.newArrayList(entity.getDepartmentCode()));
        entity.setDepartment(Optional.ofNullable(sysDictEntities).map(list->list.get(0)).map(SysDictEntity::getName).orElse(null));
        mldCustomReservationService.addEntity(entity);
        Map<String, String> templateParamMap = Maps.newHashMap();
        templateParamMap.put("time", DateUtils.format(createTime, DateUtils.DATE_TIME_PATTERN));
        templateParamMap.put("customName", entity.getCustomName());
        templateParamMap.put("customPhone", entity.getCustomPhone());
        templateParamMap.put("department", entity.getDepartment());
        //客服用户
        List<SysUserEntity> userEntityList = sysUserService.listAll(Maps.newHashMap());
        if (CollectionUtils.isEmpty(userEntityList)) {
            return;
        }
        List<String> phoneNums = userEntityList.stream().map(SysUserEntity::getMobile).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        List<String> signNames = Lists.newArrayList();
        List<Map<String, String>> templateParamList = Lists.newArrayList();
        for (int i = 0; i < phoneNums.size(); i++) {
            signNames.add("大连美琳达妇儿医院");
            templateParamList.add(templateParamMap);
        }
        try {
            SmsUtil.sendBatchSms(phoneNums, signNames, "SMS_471400108", templateParamList);
        } catch (Exception e) {
            log.warn("短信发送失败", e);
        }
    }


}
